<template>
  <Card>
    <p slot="title">编辑字典</p>
    <div
      style="display: flex; justifyContent: space-between; margin: 30px 3% 0 3%"
    >
      <div>
        <Form inline :label-width="80" >
          <FormItem label="字典名称">
            <Input placeholder="请输入字典名称" v-model.trim="formCustom.dicName"></Input>
          </FormItem>
          <Button type="primary" icon="ios-search" @click="handleSearch"
            >查询</Button
          >
          <Button style="marginLeft: 15px" @click="handleCancel">重置</Button>
        </Form>
      </div>
      <div style="float: right">
        <Button
          @click="handleCreateOrEditItem()"
          type="primary"
          icon="md-add"
          style="margin: 0 50px"
          >新建</Button
        >
      </div>
    </div>
    <Row style="margin: 5px 3% 0 3%">
      <Col span="24">
        <Table :columns="column" :data="dicData"></Table>
        <Row type="flex" justify="end" align="middle">
          <div>
            <Page
              :current="currentPageNum + 1"
              :total="dataCount"
              @on-change="handlePageChange"
              @on-page-size-change="changePage"
              show-elevator
              show-sizer
              show-total
              style="padding: 10px 10px 0 0"
            ></Page>
          </div>
        </Row>
      </Col>

    </Row>
    <div style="margin: 50px 0 0 45%">
      <Button type="primary" @click="handleReset">返回</Button>
    </div>
    <Modal
      v-model="show"
      width='30'
      :title="title"
      >
      <Form ref="formDic" :model="formDic" :rules="formDicRule" :label-width="100">
          <FormItem label="字典值" prop="dicValue" v-if= 'this.formStatus == "edit"'>
              <InputNumber
              disabled
              style="width: 85%"
              placeholder="请输入字典value"
              v-model="formDic.dicValue"
            />
          </FormItem>

          <FormItem label="字典名称" prop="dicDisplay">
            <Input
              style="width: 85%"
              v-model.trim="formDic.dicDisplay"
              placeholder="请输入字典中文名称"
            />
          </FormItem>

          <FormItem label="排序" prop="dicOrder">
            <InputNumber
              style="width: 85%"
              v-model="formDic.dicOrder"
              placeholder="搜索字典排序"
              :max=1000
            />
          </FormItem>

          <FormItem label="图标" prop="dicIcon">
            <Input
              v-model.trim="formDic.dicIcon"
              placeholder="请输入icon"
              style="width: 85%"
            />
          </FormItem>
      </Form>
      <div slot="footer">
        <Button type="primary" @click="dicSubmit('formDic')">提交</Button>
        <Button @click="dicCancel('formDic')">取消</Button>
      </div>
    </Modal>
  </Card>
</template>

<script>
import Util from '@/libs/util.js'
export default {
  name: 'editDic',
  data () {
    const validateDicDisplay = (rule, value, callback) => {
      const [url, httpConfig] = [
        `/api/validation/dicDisplay/${this.formCustom.dicType}`,
        {
          params: { display: value }
        }
      ]
      if (this.dicDisplay !== value) {
        this.$http.get(url, httpConfig).then(response => {
          if (response.data.code === -1) {
            return callback(new Error(response.data.msg))
          } else {
            return callback()
          }
        }).catch(() => {
          return callback(new Error('异步校验出错！'))
        })
      } else {
        return callback()
      }
    }
    return {
      dicDisplay: null,
      dataCount: 0,
      currentPageNum: 0,
      id: null,
      show: false,
      formStatus: 'add',
      dicData: [],
      formDicRule: {
        dicValue: [
          {
            type: 'number',
            min: 1,
            trigger: 'blur'
          }
        ],
        dicIcon: [
          {
            type: 'string',
            max: 50,
            message: 'icon最多50个字符',
            trigger: 'blur'
          }
        ],
        dicDisplay: [
          {
            required: true,
            message: '字典名称不能为空',
            trigger: 'blur'
          },
          {
            required: true,
            max: 50,
            message: '字典名称最多50个字符',
            trigger: 'blur'
          },
          { validator: validateDicDisplay, trigger: 'blur' }
        ]
      },
      formCustom: {
        dicName: null,
        size: 10,
        page: 1
      },
      formDic: {
        dicValue: null,
        dicDisplay: null,
        dicOrder: null,
        dicIcon: null
      },
      column: [
        {
          title: '字典值',
          key: 'dicValue'
        },
        {
          key: 'dicDisplay',
          title: '字典名称'
        },
        {
          key: 'dicOrder',
          title: '排序'
        },
        {
          key: 'dicIcon',
          title: '图标'
        },
        {
          title: '操作',
          width: 155,
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      this.handleCreateOrEditItem(params.row, params.index)
                    }
                  }
                },
                '编辑'
              ),
              h('span', {
                style: {
                  width: '1px',
                  backgroundColor: '#2d8cf0',
                  height: '15px',
                  display: 'inline-block',
                  verticalAlign: 'middle',
                  margin: '-2px 10px 0'
                }
              }),
              h(
                'Poptip',
                {
                  props: {
                    confirm: true,
                    title: '您确定要删除这条数据吗?',
                    transfer: true
                  },
                  on: {
                    'on-ok': () => {
                      this.deleteDic(params.index, params.row.id)
                    }
                  }
                },
                [
                  h(
                    'Button',
                    {
                      style: {
                        margin: '0 5px'
                      },
                      props: {
                        type: 'error',
                        size: 'small',
                        placement: 'top'
                      }
                    },
                    '删除'
                  )
                ]
              )
            ])
          }
        }
      ]
    }
  },
  computed: {
    title () {
      return this.formStatus === 'add' ? '新建' : '编辑'
    }
  },
  methods: {
    // 搜索
    search () {
      console.log(this.formCustom)
      let self = this
      Util.http
        .get('/api/cscpDics/getDicByType', {
          params: self.formCustom
        })
        .then(function (response) {
          self.dicData = response.data.list
          self.dataCount = response.data.total
          self.loading = false
        })
        .catch(function (error) {
          console.log(error)
        })
    },

    handleReset () {
      // this.$router.push({
      //   name: 'paramDic'
      // })
      this.closeMe()
    },
    closeMe () {
      this.$store.commit('app/closePage', {
        vm: this,
        fromName: this.$route.name,
        toName: 'paramDic'
      })
    },
    handleSearch () {
      this.search()
    },
    // 提交
    dicSubmit (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          let form = Object.assign({}, this.formDic, this.$byStoreGet('paramDicEdit'))
          if (this.formStatus === 'add') {
            Util.http.post('/api/cscpDics/addDics', form).then(() => {
              this.$Message.info('添加成功')
              this.search()
            })
          } else {
            Util.http.put('/api/cscpDics/updateDic', form).then(() => {
              this.search()
            })
          }
          this.$refs[name].resetFields()
          this.show = false
        } else {
          // this.$Message.error('提交失败')
        }
      })
    },
    // 改变一页大小
    pageNum (size) {
      this.loading = true
      this.formCustom.size = size
    },

    handleCancel () {
      this.currentPageNum = 0
      this.formCustom.page = 0
      this.formCustom.dicName = null
      this.search()
    },

    changePage (size) {
      this.loading = true
      this.formCustom.size = size
      this.search()
    },
    // 换页
    handlePageChange (pageNum) {
      this.currentPageNum = pageNum - 1
      this.formCustom.page = pageNum
      this.search()
    },

    dicCancel (name) {
      this.$refs[name].resetFields()
      this.show = false
    },
    // 删除字典
    deleteDic (index, id) {
      Util.http.delete(`/api/cscpDics/${id}`).then(res => {
        this.search()
        this.$Message.info('删除成功')
      })
    },
    // 新建、编辑
    handleCreateOrEditItem (data, index) {
      if (data) {
        this.formDic = JSON.parse(JSON.stringify(data))
        this.formStatus = 'edit'
        this.index = index
        this.dicDisplay = this.formDic.dicDisplay
      } else {
        this.formDic = {
          dicValue: null,
          dicDisplay: null,
          dicOrder: null,
          dicIcon: null
        }
        this.dicDisplay = null
        this.formStatus = 'add'
      }
      this.show = true
    }
  },
  mounted () {
    // this.formCustom.dicType = this.$route.params.type.dicType
    this.formCustom.dicType = this.$byStoreGet('paramDicEdit').dicType
    this.search()
  }
}
</script>

<style lang="less" scoped>
</style>
